package com.rongshu.sendmessage.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.adapter.QuanxianAdapter;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.bean.QuanXianBean;
import com.rongshu.sendmessage.util.httpUtil.HYContent;

import java.util.ArrayList;

public class PermissionActvity extends BaseActivity {

    private ListView listView;
    private ArrayList<QuanXianBean> mList;
    private QuanxianAdapter mAdapter;
    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission_actvity);
        mContext=this;
        initView();
        initData();

    }

    private void initView() {
        findViewById(R.id.titleLayLeft).setOnClickListener(view->finish());
        TextView title = findViewById(R.id.title);
        title.setText("系统权限管理");
        listView = findViewById(R.id.listView);
        mList=new ArrayList<>();
        mContext=this;
        mAdapter=new QuanxianAdapter(this,mList);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent=new Intent();
            String sdk = android.os.Build.VERSION.SDK; // SDK号

            String model = android.os.Build.MODEL; // 手机型号

            String release = android.os.Build.VERSION.RELEASE; // android系统版本号
            String brand = Build.BRAND;//手机厂商
            if ("redmi".equals(brand.toLowerCase()) || "xiaomi".equals(brand.toLowerCase())) {
                gotoMiuiPermission();//小米
            } else if ("meizu".equals(brand.toLowerCase())) {
                gotoMeizuPermission();
            } else if ("huawei".equals(brand.toLowerCase()) || "honor".equals(brand.toLowerCase())) {
                gotoHuaweiPermission();
            } else {
                startActivity(getAppDetailSettingIntent());
            }

        });
    }

    /**
     * 跳转到miui的权限管理页面
     */
    private void gotoMiuiPermission() {
        try { // MIUI 8
            Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", mContext.getPackageName());
            mContext.startActivity(localIntent);
        } catch (Exception e) {
            try { // MIUI 5/6/7
                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                localIntent.putExtra("extra_pkgname", mContext.getPackageName());
                mContext.startActivity(localIntent);
            } catch (Exception e1) { // 否则跳转到应用详情
                startActivity(getAppDetailSettingIntent());
            }
        }
    }

    /**
     * 跳转到魅族的权限管理系统
     */
    private void gotoMeizuPermission() {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", HYContent.APPLICATION_ID);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            startActivity(getAppDetailSettingIntent());
        }
    }

    /**
     * 华为的权限管理页面
     */
    private void gotoHuaweiPermission() {
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
            intent.setComponent(comp);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            startActivity(getAppDetailSettingIntent());
        }

    }

    /**
     * 获取应用详情页面intent（如果找不到要跳转的界面，也可以先把用户引导到系统设置页面）
     *
     * @return
     */
    private Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        return localIntent;
    }
    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    //初始化权限的
    private void initData() {
        mList.clear();
        QuanXianBean quanxianXiangce=new QuanXianBean();
        quanxianXiangce.setTitle("允许本应用访问相册权限");
        quanxianXiangce.setDes("帮您实现图片文件的保存和读取");
        boolean xiangce = checkPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE});
        quanxianXiangce.setOpen(xiangce);
        quanxianXiangce.setId(0);
        mList.add(quanxianXiangce);

        QuanXianBean quanxianCallPhone=new QuanXianBean();
        quanxianCallPhone.setTitle("允许本应用访问打电话权限");
        quanxianCallPhone.setDes("帮您实现应用带着手机号跳转至拨打电话页面");
        boolean callPhone = checkPermissions(new String[]{
                Manifest.permission.CALL_PHONE});
        quanxianCallPhone.setOpen(callPhone);
        quanxianCallPhone.setId(3);
        mList.add(quanxianCallPhone);
        QuanXianBean quanxianXiangJi=new QuanXianBean();
        quanxianXiangJi.setTitle("允许本应用访问相机权限");
        quanxianXiangJi.setDes("帮您实现拍照上传");
        boolean XiangJi = checkPermissions(new String[]{Manifest.permission.CAMERA});
        quanxianXiangJi.setOpen(XiangJi);
        quanxianXiangJi.setId(1);
        mList.add(quanxianXiangJi);

        QuanXianBean quanxianWeiZhi=new QuanXianBean();
        quanxianWeiZhi.setTitle("允许本应用访问位置权限");
        quanxianWeiZhi.setDes("帮您实现位置定位和地图定位等");
        boolean weizhi = checkPermissions(new String[]{
//                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION});
        quanxianWeiZhi.setOpen(weizhi);
        quanxianWeiZhi.setId(2);
        mList.add(quanxianWeiZhi);
        mAdapter.notifyDataSetChanged();
    }

    public void onClick(View view){
        switch (view.getId()){
            case R.id.imgBack:
                finish();
                break;
        }
    }
    /**
     * 检查是否具有多个权限
     *
     * @param permissions
     * @return true 有权限 false无权限
     */
    private boolean checkPermissions(String[] permissions) {
        for (String permission : permissions) {
            Log.e("PermissionCode", ContextCompat.checkSelfPermission(mContext, permission)+"");
            if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
}